﻿using Inovout.Gis;
using ESRI.ArcGIS.Geodatabase;
using System.Collections.Generic;
using System;
using System.Diagnostics;
using System.Threading;

namespace Inovout.ArcGis
{
    public class ArcGisSession : IGisSession
    {
        private ArcGisSessionFactory sessionFactory;
        public ArcGisSession(ArcGisSessionFactory sessionFactory)
        {
            this.sessionFactory = sessionFactory;
        }


        private IGeometryLayerInfo GetGeometryLayer(LayerMapping layerMapping)
        {
            IFeatureWorkspace workspace = sessionFactory.Workspace as IFeatureWorkspace;
            ITable arcTable = workspace.OpenTable(layerMapping.TableName);
            IGeometryLayerInfo layer = new FeatureLayerInfo(new ArcGisTable(arcTable));

            ArcGisRow r = layer.Geometries[0].Row as ArcGisRow;
            ThreadPool.SetMaxThreads(1000, 1000);

            Stopwatch stopwatch = Stopwatch.StartNew();
            ((IWorkspaceEdit)workspace).StartEditing(false);
            ((IWorkspaceEdit)workspace).StartEditOperation();

   
            //for (int i = 0; i < 9999; i++)
            //{
            //    IRow row = arcTable.CreateRow();
            //    row.set_Value(arcTable.Fields.FindField("Shape"), r.ArcFeature.ShapeCopy);
            //    row.Store();
            //}
            // Generate the thread that populates the locations table.
            //Thread t = new Thread(new ThreadStart(PopulateLocationsTableProc));
            //// Mark the thread as a single threaded apartment (STA) to efficiently run ArcObjects.
            //t.SetApartmentState(ApartmentState.STA);
            //// Start the thread.
            //t.Start();


            //http://edndoc.esri.com/arcobjects/9.2/net/2c2d2655-a208-4902-bf4d-b37a1de120de.htm


         ((IWorkspaceEdit)workspace).StopEditOperation();
            ((IWorkspaceEdit)workspace).StopEditing(true);
            stopwatch.Stop();
            return Activator.CreateInstance(layerMapping.LayerType, layer) as IGeometryLayerInfo;
        }
        void ThreadProc(int count,ITable table,IFeature feature)
        {
            for (int i = 0; i < count; i++)
            {
                IRow row = table.CreateRow();
                row.set_Value(table.Fields.FindField("Shape"), feature.ShapeCopy);
                row.Store();
            }
        }

        public IGeometryLayerInfo[] GetGeometryLayers(Type mapType)
        {
            List<IGeometryLayerInfo> geometryLayerInfos = new List<IGeometryLayerInfo>();
            foreach (LayerMapping layerMapping in sessionFactory.Configuration.GetLayerMappings(mapType))
            {
                geometryLayerInfos.Add(GetGeometryLayer(layerMapping));
            }


            return geometryLayerInfos.ToArray();
        }

    }
}
